<template>
  <div class="box-content">
    <div class="navigation">景区列表</div>
    <!--搜索-->
    <div class="mt-3">
      <el-row :gutter="10">
        <el-col :span="5">
          <el-input type="text"  size="small" v-model="search.scenic" :clearable="true" placeholder="输入关键字(景区名或用户昵称)"></el-input>
        </el-col>
        <el-col :span="13">
          <el-button type="primary" size="small" @click="onSearch">查询</el-button>
          <el-button type="primary" size="small" @click="createAccount">新增</el-button>
        </el-col>
      </el-row>
    </div>
    <!--表格-->
    <div class="mt-3">
      <el-table
              :data="userData"
              v-loading="loading"
              align="center"
              :element-loading-text="loadText"
              :header-cell-style="tableHeaderColor"
              stripe
              style="width: 100%">
        <el-table-column
                prop="id"
                align="center"
                label="编号"
                width="100"
        >
        </el-table-column>
        <el-table-column
                prop="tr_name"
                align="center"
                label="景区名"
        >
        </el-table-column>
        <!--<el-table-column-->
                <!--prop="address"-->
                <!--align="center"-->
                <!--label="景区地址"-->
        <!--&gt;-->
        <!--</el-table-column>-->
        <el-table-column
                prop="tr_desc"
                align="center"
                label="景区描述"
        >
        </el-table-column>
        <el-table-column
                align="center"
                label="地图级别"
        >
          <template slot-scope="scope">
            <div align="center" v-if="scope.row['more']">{{scope.row['more']['map_range']}}</div>
          </template>
        </el-table-column>
        <el-table-column
                prop="username"
                align="center"
                label="负责人"
                width="200"
        >
          <template slot-scope="scope">
            <div align="center" v-for="item in scope.row['bindUsers']" :key="item.id">{{item.username}}({{item.mobile}})</div>
          </template>
        </el-table-column>
        <el-table-column
                label="创建日期"
                align="center"
                width="100">
          <template slot-scope="scope">
            <div align="center">{{scope.row['created_at']?scope.row['created_at'].slice(0, 11):'无'}}</div>
            <div align="center">{{scope.row['created_at']?scope.row['created_at'].slice(11 ):'无'}}</div>
          </template>
        </el-table-column>
        <el-table-column
                align="center"
                label="景点"
        >
          <template slot-scope="scope">
            <el-button type="warning" round size="mini"  @click="$router.push({name:'scenicSpotId',params:{id: scope.row['id']}})">查看</el-button>
          </template>
        </el-table-column>
        <el-table-column
                label="操作"
                align="center"
                fixed="right"
                width="160">
          <template slot-scope="scope">
            <el-button
                    size="small"
                    type="primary"
                    @click="handleEdit(scope.row)">编辑
            </el-button>
            <el-button
                    size="small"
                    type="danger"
                    @click="handleDelete(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="mt-3 float-right">
        <el-pagination
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageInfo.current_page"
                :page-size="pageInfo.per_page"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pageInfo.total">
        </el-pagination>
      </div>
    </div>
    <!--新增对话框-->
    <el-dialog :title="dialog.title"
               :visible.sync="dialogFormVisible"
               :close-on-click-modal="false"
               width="600px">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px" v-loading="loadingDialig">
        <el-form-item label="景区名" prop="tr_name">
          <el-input v-model="form.tr_name" placeholder="请输入景区名" :clearable="true" style="width: 450px;"></el-input>
        </el-form-item>
        <el-form-item label="景区描述" prop="tr_desc">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" v-model="form.tr_desc" placeholder="请输入景区描述" :clearable="true" style="width: 450px;"></el-input>
        </el-form-item>
        <el-form-item label="景区经度" prop="longitude">
          <el-input type="number" v-model="form.longitude" placeholder="请输入景区经度" :clearable="true" style="width: 450px;"></el-input>
        </el-form-item>
        <el-form-item label="景区纬度" prop="latitude">
          <el-input type="number" v-model="form.latitude" placeholder="请输入景区纬度" :clearable="true" style="width: 450px;"></el-input>
          <el-button type="primary" :loading="loadingTransferStart" @click="transfer" style="margin-left: 10px">转换</el-button>
        </el-form-item>
        <el-form-item label="地图级别" prop="more">
          <el-input type="number" v-model="form.more" placeholder="请输入地图级别(5-18)" :clearable="true" style="width: 450px;"></el-input>
        </el-form-item>
        <!--<el-form-item label="负责人" prop="latitude"  v-if="dialog.isEdit && user.id !== ''">-->
          <!--<div style="height: 42px;width: 400px">-->
            <!--{{user.name}}({{user.mobile}}) <span class="change-user" @click="isChangeUser = true">点击修改</span>-->
          <!--</div>-->
          <!--<div>-->

          <!--</div>-->
          <!--&lt;!&ndash;<el-input type="text" disabled  style="width: 450px;">{{user.name + user.mobile}}</el-input>&ndash;&gt;-->
        <!--</el-form-item>-->
        <!--<el-form-item label="添加负责人" prop="admin_id" v-if="isChangeUser || user.id == ''">-->
          <!--<el-select v-model="form.admin_id" placeholder="请选择负责人"  :clearable="true" style="width: 450px;">-->
            <!--<el-option-->
                    <!--v-for="item in options"-->
                    <!--:key="item.id"-->
                    <!--:label="item.username + '(' + item.mobile + ')'"-->
                    <!--:value="item.id">-->
            <!--</el-option>-->
          <!--</el-select>-->
        <!--</el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" :disabled="loadingTransfer" v-if="!dialog.isEdit" :loading="loadingCreate"
                   @click="submitCostomer('form')">{{loadingCreate?'创建中':'点击创建'}}
        </el-button>
        <el-button type="primary" :disabled="loadingTransfer" v-if="dialog.isEdit" :loading="loadingCreate" @click="submitCostomer('form')">
          {{loadingCreate?'修改中':'点击修改'}}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
    import UserSearch from '../../../components/UserInfo.vue'
    export default {
        name: "ScenicList",
        components: {
            UserSearch
        },
        data() {
            var validateMore = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入地图显示级别'));
                } else {
                    if (Number(value) < 5 || Number(value) > 18) {
                        callback(new Error('地图显示级别范围在 5 到 18 !'));
                    }
                    callback();
                }
            };
            return {
                loadingTransfer:false,
                loadingTransferStart:false,
                isChangeUser: false,
                user:{
                    id: '',
                    name: '',
                    mobile: ''
                },
                baseId: null,
                inputName: '',
                pageInfo: {
                    per_page: 10,
                    total: 0,
                    current_page: 1
                },
                options:[
                    {name:'王',id:1,phone:'15928585007'},
                    {name:'李',id:2,phone:'15928585222'}
                ],
                loadText: '数据加载中',
                userData: [],
                searchStr: '',
                loading: false,
                loadingDialig: false,
                loadingCreate: false,
                dialogFormVisible: false,
                search:{
                    scenic:'', //景区名或地址
                    inputName:'' //负责人名或电话
                },
                form: {
                    tr_name: '',
                    tr_desc: '',
                    longitude:'',  // 经度
                    latitude:'',  // 纬度
                    admin_id: '',
                    more:''
                },
                dialog: {
                    title: '',
                    isEdit: false
                },
                rules: {
                    tr_name: [
                        {required: 'true', message: '请输入景区名', trigger: 'change'}
                    ], longitude: [
                        {required: 'true', message: '请输入经度', trigger: 'change'}
                    ], latitude: [
                        {required: 'true', message: '请输入纬度', trigger: 'change'}
                    ],
                    more: [
                        {validator: validateMore, trigger: 'change'}
                    ]
                }
            }
        },
        watch: {
            dialogFormVisible: function (val) {
                if (!val) {
                    Object.keys(this.form).forEach(key => this.form[key] = '');
                    this.$refs['form'].resetFields();
                    this.isChangeUser = false;
                    this.user.id = '';
                    this.user.name = '';
                    this.user.mobile = '';
                }
            }
        },
        created() {
            this.getAccountList();
        },
        methods: {
            transfer() {
                if (!this.form.longitude || !this.form.latitude) {
                    this.$message.warning('经纬度必填！否则无法转换');
                    return false;
                }
                let params = {
                    longitude: this.form.longitude,
                    latitude: this.form.latitude
                };
                this.loadingTransfer = true;
                this.loadingTransferStart = true;
                this.$http.post('api/auth/getCoords', params)
                    .then((result) => {
                        if (result.status_code == 200) {
                            this.$message({
                                type: 'success',
                                message: '转换成功',
                                during: 1000
                            });
                            this.form.longitude = result.data.x;
                            this.form.latitude = result.data.y;
                        } else {
                            this.$message.warning(result.msg);
                        }
                        this.loadingTransfer = false;
                        this.loadingTransferStart = false;
                    })
                    .catch((err) => {
                        this.loadingTransfer = false;
                            this.loadingTransferStart = false;
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            changeName(val) {
                this.search.inputName = val;
            },
            createAccount() {
                this.dialog.title = '添加景区';
                this.dialog.isEdit = false;
                this.dialogFormVisible = true;
            },
            getAccountList() {
                this.loading = true;
                this.$http.get('api/auth/tourismResort' + this.searchStr, {
                    params: {
                        pageSize: this.pageInfo.per_page,
                        page: this.pageInfo.current_page
                    }
                })
                    .then((result) => {
                        if (result.status_code == 200) {
                            this.userData = result.data.data;
                            this.pageInfo.total = result.data.total;
                        } else {
                            this.$message.warning(result.msg);
                        }
                        this.loading = false;
                    })
                    .catch((err) => {
                        this.loading = false;
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            onSearch() {
                this.searchStr = "";
                if (this.search.scenic) {
                    this.addConStr();
                    this.searchStr += `keyword=${this.search.scenic}`;
                }
                this.pageInfo.current_page = 1;
                this.getAccountList();
            },
            addConStr() {
                if (this.searchStr.length > 0) {
                    this.searchStr += '&';
                } else {
                    this.searchStr += '?';
                }
            },
            submitCostomer(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.creatShanHu();
                    } else {
                        return false;
                    }
                });
            },
            creatShanHu() {
                this.loadingCreate = true;
                let params;
                if (this.dialog.isEdit) {
                    params={
                        tr_name:this.form.tr_name,
                        longitude:this.form.longitude,
                        latitude:this.form.latitude,
                        tr_desc:this.form.tr_desc,
                        more:{map_range:this.form.more}
                        // user_id:this.form.admin_id
                    };
                    if (this.form.admin_id) {
                        Object.assign(params, {user_id:this.form.admin_id});
                    }
                    this.$http.put('api/auth/tourismResort/' + this.baseId, params)
                        .then((result) => {
                            if (result.status_code == 200) {
                                this.$message({
                                    type: 'success',
                                    message: result.msg,
                                    during: 1000
                                });
                                this.getAccountList();
                                this.dialogFormVisible = false;
                            } else {
                                this.$message.warning(result.msg);
                            }
                            this.loadingCreate = false;
                        })
                        .catch((err) => {
                            this.loadingCreate = false;
                            this.$message.warning(err.data.msg || "数据异常，请重试");
                        })
                } else {
                    params={
                        tr_name:this.form.tr_name,
                        longitude:this.form.longitude,
                        latitude:this.form.latitude,
                        tr_desc:this.form.tr_desc,
                        more:{map_range:this.form.more}
                    };
                    this.$http.post('api/auth/tourismResort', params)
                        .then((result) => {
                            if (result.status_code == 200) {
                                this.$message({
                                    type: 'success',
                                    message: result.msg,
                                    during: 1000
                                });
                                this.getAccountList();
                                this.dialogFormVisible = false;
                            } else {
                                this.$message.warning(result.msg);
                            }
                            this.loadingCreate = false;

                        })
                        .catch((err) => {
                            this.loadingCreate = false;
                            this.$message.warning(err.data.msg || "数据异常，请重试");
                        })
                }

            },
            handleEdit(val) {
                this.baseId = val.id;
                this.dialog.title = '编辑景区';
                this.dialog.isEdit = true;
                this.dialogFormVisible = true;
                this.loadingDialig = true;
                // this.getUnUserAdmin(); // 获取未被指派为负责人的管理员列表
                this.getOneTable(val);
            },
            getUnUserAdmin() {
                this.$http.get('api/system/admin?@action=unBindAdminList')
                    .then((result) => {
                        if (result.status_code == 200) {
                          this.options = result.data.data;
                        } else {
                            this.$message.warning(result.msg);
                        }

                    })
                    .catch((err) => {
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            getOneTable(val){
                this.$http.get('api/auth/tourismResort/' + val.id)
                    .then((result) => {
                        if (result.status_code == 200) {
                            this.form.tr_name = result.data.tr_name;
                            this.form.longitude = result.data.longitude;
                            this.form.latitude = result.data.latitude;
                            // this.form.admin_id = result.data.user_id;
                            this.form.tr_desc = result.data.tr_desc;
                            this.form.more = result.data.more?result.data.more.map_range:'';
                            if (result.data.user_id) {
                                this.user.id = result.data.user_id,
                                this.user.name = result.data.username,
                                this.user.mobile = result.data.mobile
                            }
                        } else {
                            this.$message.warning(result.msg);
                        }
                        this.loadingDialig = false;
                    })
                    .catch((err) => {
                        this.loadingDialig = false;
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            handleDelete(val) {
                this.$confirm('此操作将删除景区, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$http.delete('/api/auth/tourismResort/' + val.id)
                        .then((result) => {
                            if (result.status_code == 200) {
                                this.$message({
                                    type: 'success',
                                    message: result.msg,
                                    during: 1000
                                });
                                this.getAccountList();
                            } else {
                                this.$message.warning(result.msg);
                            }
                        })
                        .catch((err) => {
                            this.$message.warning(err.data.msg || "数据异常，请重试");
                        })
                }).catch(() => {
                });
            },
            handleSizeChange(val) {
                this.pageInfo.current_page = 1;
                this.pageInfo.per_page = val;
                this.getAccountList();
            },
            handleCurrentChange(val) {
                this.pageInfo.current_page = val;
                this.getAccountList();
            },
            tableHeaderColor({row, column, rowIndex, columnIndex}) {
                if (rowIndex === 0) {
                    return 'background-color: #FAFAFA;color: #000;font-weight: 500;height:54px;font-size:14px'
                }
            },
        }
    }
</script>

<style lang="less">

  .change-user{
    color: #409EFF;
  }
  .change-user:hover{
    cursor: pointer;
    color: #66b1ff;
  }
</style>